<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />

    

    

    <title>springboot集成redis集群 | 郑礼德技术栈</title>
    <meta name="author" content="郑礼德" />
    <meta name="keywords" content="" />
    <meta name="description" content="本文介绍如何搭建redis集群，以及springboot集成redis搭建redis集群安装redis安装gcc-c++ ruby rubygem 依赖包yum install -y gcc-c++ yum install -y ruby rubygems集群需要用到ruby 语言，redis-trib.rb 脚本是redis 和ruby的接口脚本，用于启动集群上传并解压redis安装包tar -xvf redis-3.0.0.tar.gz -C /usr/local安装re..." />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />

    
    <link rel="alternate" href="/homepage/atom.xml" title="郑礼德技术栈" type="application/atom+xml">
    
    
    <link rel="icon" href="/homepage/images/favicon.ico">
    

    <style type="text/css">
    @font-face {
        font-family: 'icomoon';
        src: url("/homepage/fonts/icomoon.eot?q628ml");
        src: url("/homepage/fonts/icomoon.eot?q628ml#iefix") format('embedded-opentype'),
             url("/homepage/fonts/icomoon.ttf?q628ml") format('truetype'),
             url("/homepage/fonts/icomoon.woff?q628ml") format('woff'),
             url("/homepage/fonts/icomoon.svg?q628ml#icomoon") format('svg');
        font-weight: normal;
        font-style: normal;
    }
    </style>
    
<link rel="stylesheet" href="/homepage/css/style.css">


    <!--[if lt IE 9]>
    <style type="text/css">
    .nav-inner {top:0;}
    .author-meta {position:static;top:0;}
    .search-form {height:36px;}
    </style>
    <script type="text/javascript" src="https://unpkg.com/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <![endif]-->
<meta name="generator" content="Hexo 4.2.0"></head>
<body>

    <main class="app">
        <header id="header" class="header clearfix">
    <div id="nav" class="nav">
    <div class="nav-mobile">
        <button id="open-panel" class="open-panel nav-mobile-item"><i class="icon-documents"></i></button>
        <h1 class="nav-mobile-title nav-mobile-item">郑礼德技术栈</h1>
        <button id="open-menus" class="open-panel nav-mobile-item"><i class="icon-library"></i></button>
    </div>

    <nav id="nav-inner" class="nav-inner">
        
            <a class="nav-item" href="/homepage/">
                <span class="nav-text">首页</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/front-end">
                <span class="nav-text">前端</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/back-end">
                <span class="nav-text">后端</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/linux">
                <span class="nav-text">linux部署</span>
            </a>
        
            <a class="nav-item" href="/homepage/tags">
                <span class="nav-text">标签</span>
            </a>
        
            <a class="nav-item" href="/homepage/archives">
                <span class="nav-text">归档</span>
            </a>
        
            <a class="nav-item" href="/homepage/about">
                <span class="nav-text">关于</span>
            </a>
        
    </nav>
</div>

    <aside id="aside" class="aside">
    <div id="aside-mask" class="aside-mask"></div>
    <div id="aside-inner" class="aside-inner">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"><i class="icon-search-stroke"></i></button><input type="hidden" name="sitesearch" value="http://zhenglide.gitee.io/homepage"></form>

        
        
        
        

        
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#搭建redis集群"><span class="toc-number">1.</span> <span class="toc-text">搭建redis集群</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#安装redis"><span class="toc-number">1.1.</span> <span class="toc-text">安装redis</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#安装gcc-c-ruby-rubygem-依赖包"><span class="toc-number">1.1.1.</span> <span class="toc-text">安装gcc-c++ ruby rubygem 依赖包</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#上传并解压redis安装包"><span class="toc-number">1.1.2.</span> <span class="toc-text">上传并解压redis安装包</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#安装redis-1"><span class="toc-number">1.1.3.</span> <span class="toc-text">安装redis</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#搭建集群"><span class="toc-number">1.2.</span> <span class="toc-text">搭建集群</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#集群配置"><span class="toc-number">1.2.1.</span> <span class="toc-text">集群配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#报错处理"><span class="toc-number">1.2.2.</span> <span class="toc-text">报错处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#测试"><span class="toc-number">1.2.3.</span> <span class="toc-text">测试</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#redis-集成springboot"><span class="toc-number">2.</span> <span class="toc-text">redis 集成springboot</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#添加依赖"><span class="toc-number">2.1.</span> <span class="toc-text">添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#yml配置文件"><span class="toc-number">2.2.</span> <span class="toc-text">yml配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RedisConfig"><span class="toc-number">2.3.</span> <span class="toc-text">RedisConfig</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RedisUtils工具类自由操作redis"><span class="toc-number">2.4.</span> <span class="toc-text">RedisUtils工具类自由操作redis</span></a></li></ol></li></ol>
        
    </div>
</aside>

</header>

        <div id="content" class="content">
            <div id="wrapper" class="wrapper" style="max-width: 800px">
                <article class="article" itemscope itemprop="blogPost">
    
    <header class="article-header">
        
        <h1 itemprop="name">
            springboot集成redis集群
        </h1>
        
        <div class="article-meta clearfix">
            <a class="article-date" href="http://zhenglide.gitee.io/homepage/2020/10/20/springboot%E9%9B%86%E6%88%90redis%E9%9B%86%E7%BE%A4/index.html">
    
    <i class="icon-calendar"></i>
    
    <time datetime="2020-10-20T06:59:30.000Z" itemprop="datePublished">2020-10-20</time>
</a>

            
<div class="article-tag-list">
    <i class="icon-tag"></i>
    <a class="article-tag-link" href="/homepage/tags/redis/" rel="tag">redis</a>, <a class="article-tag-link" href="/homepage/tags/springboot/" rel="tag">springboot</a>
</div>


        </div>
    </header>
    
    <section class="article-body markdown-body">
        
        <p>本文介绍如何搭建redis集群，以及springboot集成redis</p>
<a id="more"></a>

<h2 id="搭建redis集群"><a href="#搭建redis集群" class="headerlink" title="搭建redis集群"></a>搭建redis集群</h2><h3 id="安装redis"><a href="#安装redis" class="headerlink" title="安装redis"></a>安装redis</h3><h4 id="安装gcc-c-ruby-rubygem-依赖包"><a href="#安装gcc-c-ruby-rubygem-依赖包" class="headerlink" title="安装gcc-c++ ruby rubygem 依赖包"></a>安装gcc-c++ ruby rubygem 依赖包</h4><pre><code class="sh">yum install -y gcc-c++ </code></pre>
<pre><code class="sh">yum install -y ruby rubygems</code></pre>
<p>集群需要用到ruby 语言，redis-trib.rb 脚本是redis 和ruby的接口脚本，用于启动集群</p>
<h4 id="上传并解压redis安装包"><a href="#上传并解压redis安装包" class="headerlink" title="上传并解压redis安装包"></a>上传并解压redis安装包</h4><pre><code class="sh">tar -xvf redis-3.0.0.tar.gz -C /usr/local</code></pre>
<h4 id="安装redis-1"><a href="#安装redis-1" class="headerlink" title="安装redis"></a>安装redis</h4><pre><code>cd /usr/local/redis-3.0.0</code></pre><p> 编译 安装redis</p>
<pre><code class="sh">make &amp;&amp; make PREFIX=/usr/local/redis install</code></pre>
<p>复制多几个目录用于集群环境搭建</p>
<pre><code class="sh">mkdir redis500{1,2,3,4,5,6}</code></pre>
<p>并把安装好的redis的redis-server等文件拷贝过去，把几个节点目录放到/usr/local/redis目录 方便管理 ,在redis目录下再新建 log 目录</p>
<h3 id="搭建集群"><a href="#搭建集群" class="headerlink" title="搭建集群"></a>搭建集群</h3><h4 id="集群配置"><a href="#集群配置" class="headerlink" title="集群配置"></a>集群配置</h4><p>配置redis.conf 分别放到redis5001 redis5002 redis5003 redis5004 redis5005 redis5006下面只列举5001 配置</p>
<pre><code>
#端口号
port 5001
#yes启动守护进程
appendonly yes
#启动集群
cluster-enabled yes
#关联集群配置文件
cluster-config-file &quot;nodes.conf&quot;
#设置超时
cluster-node-timeout 5000
#日志文件 
logfile &quot;/usr/local/redis/log/redis-01.log&quot;

#指定访问的Ip地址，0.0.0.0 表示所有IP 可访问
bind 0.0.0.0
#最大 内存设置
maxmemory 262144000
#设置密码
requirepass zhenglide_123
masterauth zhenglide_123</code></pre><p>在redis根目录下创建并编辑启动脚本start.sh，使用redis-server redis.conf 启动</p>
<pre><code class="shell">echo &#39;停止进程&#39;
ps -ef|grep redis|grep -v &#39;grep&#39; |awk &#39;{print $2}&#39;|xargs kill -9
cd redis5001
./redis-server ./redis.conf &amp;
cd ../redis5002
./redis-server ./redis.conf &amp;
cd ../redis5003
./redis-server ./redis.conf &amp;
cd ../redis5004
./redis-server ./redis.conf &amp;
cd ../redis5005
./redis-server ./redis.conf &amp;
cd ../redis5006
./redis-server ./redis.conf &amp;

echo &quot;start redis  success&quot;</code></pre>
<p>chmod 777 start.sh</p>
<p>启动 start.sh </p>
<p>从解压后的redis-3.0.0 中拷贝脚本redis-trib.sh到redis根目录下,并创建集群</p>
<pre><code class="sh">./redis-trib.rb create --replicas  1  127.0.0.1:5001  127.0.0.1:5002  127.0.0.1:5003  127.0.0.1:5004  127.0.0.1:5005  127.0.0.1:5006</code></pre>
<h4 id="报错处理"><a href="#报错处理" class="headerlink" title="报错处理"></a>报错处理</h4><p>错误</p>
<p>如报了一下错误：</p>
<p>/usr/share/rubygems/rubygems/core_ext/kernel_require.rb:55:in `require’: cannot load such file – redis (LoadError)</p>
<p>​    from /usr/share/rubygems/rubygems/core_ext/kernel_require.rb:55:in `require’</p>
<p>​    from ./redis-trib.rb:25:in `<main>‘</p>
<p>在<a href="https://rubygems.org/gems/redis/" target="_blank" rel="noopener">https://rubygems.org/gems/redis/</a> 下载对应版本的gem 包，放在redis目录，并使用以下命令安装</p>
<pre><code class="sh">gem install redis -v 3.3.0 或gem install redis-3.3.0.gem</code></pre>
<p>然后在client.rb 修改密码</p>
<p>:password =&gt; “zhenglide_123”</p>
<p>重启</p>
<pre><code class="sh">./redis-trib.rb create --replicas  1  127.0.0.1:5001  127.0.0.1:5002  127.0.0.1:5003  127.0.0.1:5004  127.0.0.1:5005  127.0.0.1:5006</code></pre>
<pre><code></code></pre><h4 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h4><p>redis-cli -p 5001 -c</p>
<h2 id="redis-集成springboot"><a href="#redis-集成springboot" class="headerlink" title="redis 集成springboot"></a>redis 集成springboot</h2><h3 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h3><pre><code class="xml">&lt;dependency&gt;
   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;
&lt;/dependency&gt;</code></pre>
<h3 id="yml配置文件"><a href="#yml配置文件" class="headerlink" title="yml配置文件"></a>yml配置文件</h3><pre><code class="yml">spring:
  redis:
    cluster:
      nodes: 192.168.1.128:5001,192.168.1.128:5002,192.168.1.128:5003,192.168.1.128:5004,192.168.1.128:5005,192.168.1.128:5006
    database: 0
    password: zhenglide_123
    jedis:
      pool:
        max-active: 8 # 连接池最大连接数（使用负值表示没有限制）
        max-wait: -1ms # 连接池最大阻塞等待时间（使用负值表示没有限制）
        max-idle: 8 # 连接池中的最大空闲连接
        min-idle: 0 # 连接池中的最小空闲连接
    timeout: 3000ms
server:
  port: 9091
</code></pre>
<h3 id="RedisConfig"><a href="#RedisConfig" class="headerlink" title="RedisConfig"></a>RedisConfig</h3><p> 为redisTemplate 配置序列化</p>
<pre><code class="java">/**
 * Redis配置类
 *
 */
@EnableCaching
@Configuration
public class RedisConfig  {

    /**
     * redis数据库自定义key
     */
    public  static final String REDIS_KEY_DATABASE=&quot;zhenglide&quot;;

    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisSerializer&lt;Object&gt; serializer = redisSerializer();
        RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate&lt;&gt;();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisSerializer&lt;Object&gt; redisSerializer() {
        //创建JSON序列化器
        Jackson2JsonRedisSerializer&lt;Object&gt; serializer = new Jackson2JsonRedisSerializer&lt;&gt;(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //设置Redis缓存有效期为1天
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }

}</code></pre>
<h3 id="RedisUtils工具类自由操作redis"><a href="#RedisUtils工具类自由操作redis" class="headerlink" title="RedisUtils工具类自由操作redis"></a>RedisUtils工具类自由操作redis</h3><pre><code class="java">/**
 * redis操作实现类
 *
 */
@Component
public class RedisUtils  {
    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    public Long del(List&lt;String&gt; keys) {
        return redisTemplate.delete(keys);
    }

    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    public Boolean hSet(String key, String hashKey, Object value, long time) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return expire(key, time);
    }

    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public Map&lt;Object, Object&gt; hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public Boolean hSetAll(String key, Map&lt;String, Object&gt; map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        return expire(key, time);
    }

    public void hSetAll(String key, Map&lt;String, Object&gt; map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }

    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    public Set&lt;Object&gt; sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    public Long sAdd(String key, Object... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    public Long sAdd(String key, long time, Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return count;
    }

    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    public List&lt;Object&gt; lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }


    public Long lPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    public Long lPush(String key, Object value, long time) {
        Long index = redisTemplate.opsForList().rightPush(key, value);
        expire(key, time);
        return index;
    }


    public Long lPushAll(String key, Object... values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    public Long lPushAll(String key, Long time, Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        expire(key, time);
        return count;
    }

    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }
}</code></pre>

        
    </section>
</article>



<a id="pagenext" href="/homepage/2020/09/22/%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83%E7%BB%93%E5%90%88mysql%E4%BD%BF%E7%94%A8/" class="article-next" title="配置中心结合mysql使用"><i class="icon-arrow-right"></i></a>


<a id="pageprev" href="/homepage/2020/10/20/%E4%BD%BF%E7%94%A8mycat%E6%90%AD%E5%BB%BA%E6%95%B0%E6%8D%AE%E5%BA%93%E9%9B%86%E7%BE%A4%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB/" class="article-prev" title="使用mycat搭建数据库集群读写分离"><i class="icon-arrow-left"></i></a>




            </div>
        </div>
        <footer class="footer">
    Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>, Theme by <a href="https://github.com/sanonz/hexo-theme-concise" target="_blank">Concise</a>

    
    <script>
        var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?b13bb4c2ef8300062aab9732bd22eae0";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>
    
</footer>

    </main>

    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        var nodes = {
            nav: $('#nav'),
            aside: $('#aside'),
            asideInner: $('#aside-inner'),
            navInner: $('#nav-inner')
        };

        var doing = false;
        nodes.asideInner.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd oanimationend animationend', function() {
            if (nodes.aside.hasClass('mobile-open')) {
                nodes.aside.removeClass('mobile-open');
            } else {
                nodes.aside.removeClass('mobile-close panel-show');
            }
            doing = false;
        });
        $('#open-panel, #aside-mask').on('click', function() {
            if (doing) {
                return;
            }

            if (nodes.aside.hasClass('panel-show')) {
                nodes.aside.addClass('mobile-close');
            } else {
                nodes.aside.addClass('mobile-open panel-show');
            }
        });
        $('#open-menus').on('click', function() {
            nodes.navInner.slideToggle();
        });

        if (window.innerWidth <= 960) {
            setTimeout(function() {
                nodes.navInner.slideUp();
            }, 3000);
        }
    });
    </script>
    
        
<script src="/homepage/js/scrollspy.min.js"></script>

        <script type="text/javascript">
        $(document.body).scrollspy({target: '#aside-inner'});

        $(window).on('resize', function() {
            var hw = $('#header').width();
            var ww = $('#wrapper').width();
            var space = ($(this).width() - hw - ww) / 2 / 2;

            var pageprev = $('#pageprev');
            var pagenext = $('#pagenext');
            var avg = (pageprev.width() + pagenext.width()) / 2

            if(space > avg) {
                var len = space - avg / 2;
                var styles = {position: 'fixed', top: '50%', marginTop: - (pageprev.width() + pagenext.width()) / 4}
                pageprev.css($.extend({left: hw + len}, styles));
                pagenext.css($.extend({right: len}, styles));
            } else {
                pageprev.removeAttr('style');
                pagenext.removeAttr('style');
            }
        }).trigger('resize');
        </script>
    

</body>
</html>
